package com.web.security.service;

import com.web.dao.UserInfoDao;
import com.web.pojo.domain.Permission;
import com.web.pojo.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wws
 * @Date: 2021/2/6 0:48
 * describe:
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    UserInfoDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("NONE_PROVIDED".equals(username) || "".equals(username)){
            throw new UsernameNotFoundException("用户名为空");
        }
        //1.根据用户名去数据库查询
        UserInfo userInfo = userDao.selectUserByUserName(username);
        if(null==userInfo){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询权限
        List<Permission> permissions = userDao.selectPermissionByUserId(userInfo.getUserId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        for (Permission permission : permissions) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl());
            grantedAuthorities.add(grantedAuthority);
        }
        return new User(userInfo.getUsername(),userInfo.getPassword(), grantedAuthorities);
    }
}
